package com.jjlin.chapter_2;

import java.util.*;
public class CD110{
    public static class Node{
        public int val;
        public Node next;
        public Node(int data){
            this.val = data;
        }
    }

    public static int josephusKill(Node head, int m){
        if(head == null || head.next == head)
            return -1;
        Node cur = head.next;
        int size = 1;
        while(cur != head){
            size++;
            cur = cur.next;
        }
        int winner = getWinnerIndex(size, m);
        cur = head;
        while(winner-- > 0)
            cur = cur.next;
        return cur.val;
    }

    public static int getWinnerIndex(int size, int m){
        if(size < 1 || m < 1)
            return -1;
        int winner = 0;
        for(int i = 2; i <= size; i++)
            winner = (winner + m) % i;
        return winner;
        //不知道为什么递归过不了
//         if(size == 1)
//             return 0;
//         return (getWinnerIndex(size - 1, m) + m) % size;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        Node head = new Node(1);
        Node last = head;
        for(int i = 2; i <= n; i++){
            Node cur = new Node(i);
            last.next = cur;
            last = cur;
        }
        last.next = head;
        System.out.print(josephusKill(head, m));
    }
}
